﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace net.entity.framework.db {
    internal abstract class DbBulkCopy {
        public DataProvider Provider { get; private set; }
        public string DestinationTableName { get; set; }
        public Dictionary<string, string> ColumnMappings { get; set; }

        protected DbBulkCopy(DataProvider provider) {
            Provider = provider;
        }

        public static DbBulkCopy Create(DataProvider provider) {
            if (provider.Client.Type == DbClient.SqlClient.Type) {
                return new SqlBulkCopy(provider);
            }
            throw new NotImplementedException();
        }

        public abstract void WriteToServer(DataTable dataTable);
    }

    internal sealed class SqlBulkCopy : DbBulkCopy {
        public SqlBulkCopy(DataProvider provider) : base(provider) {}

        public override void WriteToServer(DataTable dataTable) {
            var sqlConnection = (SqlConnection) Provider.GetConnection(false);
            var sqlTransaction = (SqlTransaction) Provider.GetTransaction(false);
            var sbc = new System.Data.SqlClient.SqlBulkCopy(sqlConnection,
                                                            SqlBulkCopyOptions.Default,
                                                            sqlTransaction)
                      {DestinationTableName = DestinationTableName};
            foreach (var mapping in ColumnMappings) {
                sbc.ColumnMappings.Add(mapping.Key, mapping.Value);
            }
            sbc.WriteToServer(dataTable);
        }
    }
}